package com.zzyl.nursing.service.impl;


import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class WechatServiceImpl implements WechatService {

    private static final String REQUEST_URL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";

    // 获取token
    private static final String TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";

    // 获取手机号
    private static final String PHONE_REQUEST_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";


    @Value("${wechat.appid}")
    private String appid;

    @Value("${wechat.secret}")
    private String secret;

    @Override
    public String getOpenId(String code) {
        Map<String,Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",code);
        String s = HttpUtil.get(REQUEST_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        Object errcode = jsonObject.get("errcode");
        if(ObjectUtil.isNotEmpty(errcode)){
            throw new BaseException(jsonObject.get("errmsg").toString());
        }
        String openid = (String) jsonObject.get("openid");
        return openid;
    }

    @Override
    public String getPhone(String phoneCode) {
        //获取access_token
        Map<String,Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        String s = HttpUtil.get(TOKEN_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(s);
        String accessToken = (String) jsonObject.get("access_token");

        //获取手机号
        Map<String,Object> phoneMap = new HashMap<>();
        phoneMap.put("code",phoneCode);
        String post = HttpUtil.post(PHONE_REQUEST_URL + accessToken, JSONUtil.toJsonStr(phoneMap));

        JSONObject jsonObjectPhone = JSONUtil.parseObj(post);
        Integer errcode = (Integer) jsonObjectPhone.get("errcode");
        if (!errcode.equals(0)) {
            throw new BaseException(jsonObjectPhone.get("errmsg").toString());
        }
        JSONObject object = (JSONObject) jsonObjectPhone.get("phone_info");
        String phoneNumber = (String) object.get("phoneNumber");

        return phoneNumber;
    }
}
